import Vue from 'vue'
import Router from 'vue-router'
import layout from '@/views/layout'
import Cookies from "js-cookie"

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path:'/',
      redirect:'login'
    },
    {
      path: '/',
      name: 'layout',
      component: layout,
      children:[
        {
          path:'/home',
          name:"home",
          component: _=>import("@/views/home/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/user',
          name:"user",
          component: _=>import("@/views/manage-user/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/answer',
          name:"answer",
          component: _=>import("@/views/manage-answer/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/searchList',
          name:"search",
          component: _=>import("@/views/search/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/problem',
          name:"problem",
          component: _=>import("@/views/barrier/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/category',
          name:"category",
          component: _=>import("@/views/manage-category/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/level',
          name:"level",
          component: _=>import("@/views/manage-level/index"),
          meta:{
            requireAuth:true
          }
        },
        {
          path:'/memory',
          name:"memory",
          component: _=>import("@/views/manage-memory/index"),
          meta:{
            requireAuth:true
          }
        },{
          path:'/banner',
          name:"banner",
          component: _=>import("@/views/manage-banner/index"),
          meta:{
            requireAuth:true
          }
        },
        {
          path:'/school',
          name:"school",
          component: _=>import("@/views/manage-school/index"),
          meta:{
            requireAuth:true
          }
        }
      ]
    },
    {
      path:'/login',
      name:'login',
      component: _=>import("@/views/login/index")
    }
  ]
})

//重复点击
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (Cookies.get('token')) {
      next();
    } else {
      next({
        path: '/login',
      })
    }
  }
  else {
    next();
  }
})

export default router
